package com.stxx.stiot2.service.impl;

import cn.dev33.satoken.secure.BCrypt;
import com.stxx.framwork.domain.model.PageQuery;
import com.stxx.framwork.domain.model.PageResult;
import com.stxx.framwork.utils.StoreUtils;
import com.stxx.stiot2.domain.SysSocial;
import com.stxx.stiot2.domain.SysUser;
import com.stxx.stiot2.service.SysSocialService;
import com.stxx.stiot2.service.SysUserService;
import me.zhyd.oauth.model.AuthUser;
import org.noear.solon.annotation.Component;
import org.noear.solon.annotation.Inject;
import org.noear.solon.data.sql.SqlBuilder;

import java.sql.SQLException;
import java.time.LocalDateTime;
import java.util.List;

/**
 * @author Fuzhenlei
 * @date 2025-05-26 15:55:45
 */
@Component
public class SysSocialServiceImpl implements SysSocialService{
    @Inject
    StoreUtils storeUtils;
    @Inject
    SysUserService userService;

    @Override
    public SysSocial queryById(String id) {
        try {
            return storeUtils.selectById(id,SysSocial.class);
        } catch (SQLException e) {
            throw new RuntimeException(e);
        }
    }

    @Override
    public int insert(SysSocial bean) throws SQLException {
        validEntityBeforeSave(bean);
        return storeUtils.insert(bean);
    }

    @Override
    public int update(SysSocial bean) throws SQLException {
        validEntityBeforeSave(bean);
        return storeUtils.update(bean);
    }

    @Override
    public int update(SysSocial bean, Boolean ignoreNull) throws SQLException {
        validEntityBeforeSave(bean);
        return storeUtils.update(bean,ignoreNull);
    }

    /**
     * 保存前的数据校验
     */
    private void validEntityBeforeSave(SysSocial bean){

    }



    @Override
    public int delete(String name) throws SQLException {
        return storeUtils.delete(SysSocial.class,name);
    }

    @Override
    public int deleteByIds(String[] ids) throws SQLException {
        return storeUtils.deleteByIds(SysSocial.class, ids);
    }

    @Override
    public List<SysSocial> list(SysSocial obj) throws SQLException {
        return storeUtils.selectList(SysSocial.class,obj);
    }

    @Override
    public PageResult<SysSocial> pageList(SysSocial obj, PageQuery pageQuery) throws SQLException {
        return storeUtils.selectPageList(SysSocial.class,obj,pageQuery);
    }

    @Override
    public SysSocial queryByOpenId(String source, String openId) throws SQLException {
        SqlBuilder sb = new SqlBuilder();
        sb.append("select * from ").append(StoreUtils.getTableName(SysSocial.class))
                .append(" where source=? and open_id=? ",source,openId);
        return storeUtils.sql(sb).queryRow(SysSocial.class);
    }

    @Override
    public SysUser loginUser(AuthUser user) throws SQLException {
        SysSocial social = this.queryByOpenId(user.getSource(),user.getUuid());
        if(social==null){
            social = new SysSocial();
            social.setOpenId(user.getUuid());
            social.setNickname(user.getNickname());
            social.setAvatar(user.getAvatar());
            social.setCreateTime(LocalDateTime.now());
            social.setUsername(user.getUsername());
            social.setSource(user.getSource());
            com.alibaba.fastjson.JSONObject jsonObject = user.getRawUserInfo();
            if(jsonObject!=null){
                social.setRawUserInfo(jsonObject.toJSONString());
                social.setPhoneNo(jsonObject.getString("phone_number"));
            }
            this.insert(social);
        }
        SysUser user1 = null;
        if(social.getUserId()!=null){
            user1 = userService.queryById(social.getUserId());
        }
        if(user1==null){
            user1 = userService.queryByUsername(user.getUsername());
            //如果没有匹配的用户，直接创建
            if(user1==null){
                user1 = new SysUser();
                user1.setUserName(user.getUsername());
                user1.setNickname(user.getNickname());
                user1.setPassword(BCrypt.hashpw("123456"));
                user1.setLastLoginTime(LocalDateTime.now());
                userService.insert(user1);
            }
            social.setUserId(user1.getUserId());
            this.update(social);
        }
        return user1;
    }
}
